<template>
  <div class="guide-manage-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>解说员管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleRefresh"
        >刷新</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="解说员姓名">
          <el-input v-model="queryParams.name" placeholder="请输入解说员姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="可预约" value="AVAILABLE"></el-option>
            <el-option label="不可预约" value="UNAVAILABLE"></el-option>
            <!-- <el-option label="离职" value="INACTIVE"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格区域 -->
      <el-table
        :data="guideList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="gender" label="性别" align="center">
          <template slot-scope="scope">
            {{ scope.row.gender === 'MALE' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="language" label="专长领域" align="center"></el-table-column>
        <el-table-column prop="introduction" label="个人简介" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <!-- <el-tag type="success" v-if="scope.row.status === 'ACTIVE'">在职</el-tag>
            <el-tag type="warning" v-else-if="scope.row.status === 'ON_LEAVE'">休假</el-tag>
            <el-tag type="info" v-else-if="scope.row.status === 'INACTIVE'">离职</el-tag>
            <el-tag v-else>未知</el-tag> -->
            <el-tag type="success" v-if="scope.row.status === 'AVAILABLE'">可预约</el-tag>
            <el-tag type="warning" v-else-if="scope.row.status === 'UNAVAILABLE'">不可预约</el-tag>
            <el-tag v-else>未知</el-tag>
            
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      ></el-pagination>
      
      <!-- 编辑解说员对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
        <el-form :model="guideForm" :rules="rules" ref="guideFormRef" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="guideForm.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="guideForm.gender">
              <el-radio label="MALE">男</el-radio>
              <el-radio label="FEMALE">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="联系电话" prop="phone">
            <el-input v-model="guideForm.phone"></el-input>
          </el-form-item> -->
          <el-form-item label="专长领域" prop="language">
            <el-input v-model="guideForm.language"></el-input>
          </el-form-item>
          <el-form-item label="个人简介" prop="introduction">
            <el-input type="textarea" v-model="guideForm.introduction" rows="4"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="guideForm.status" placeholder="请选择状态">
              <!-- <el-option label="在职" value="ACTIVE"></el-option>
              <el-option label="休假" value="ON_LEAVE"></el-option>
              <el-option label="离职" value="INACTIVE"></el-option> -->
              <el-option label="可预约" value="AVAILABLE"></el-option>
              <el-option label="不可预约" value="UNAVAILABLE"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像" prop="photo">
            <div class="avatar-uploader">
              <div class="el-upload" @click="handleImageClick">
                <img v-if="guideForm.photo" :src="guideForm.photo && guideForm.photo.startsWith('data:image') ? guideForm.photo : 'data:image/jpeg;base64,' + guideForm.photo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input
                type="file"
                ref="fileInput"
                style="display: none"
                accept="image/*"
                @change="handleFileChange"
              >
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'GuideManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        name: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      // 解说员列表
      guideList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框可见性
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 是否为编辑模式
      editMode: false,
      // 解说员表单
      guideForm: {
        id: '',
        name: '',
        gender: 'MALE',
        // phone: '',
        language: '',
        introduction: '',
        status: '可预约',
        photo: ''
      },
      // 上传头信息
      uploadHeaders: {
        Authorization: localStorage.getItem('token')
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        // phone: [
        //   { required: true, message: '请输入联系电话', trigger: 'blur' },
        //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        // ],
        language: [
          { required: true, message: '请输入专长领域', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 获取解说员列表
    this.getGuideList()
  },
  methods: {
    // 获取解说员列表
    async getGuideList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/guide/list', {
          params: this.queryParams
        })
        if (res.code !== 200) {
          return this.$message.error(res.message || '获取解说员列表失败')
        }
        this.guideList = res.data.records
        this.total = res.data.total
      } catch (error) {
        console.error('获取解说员列表失败', error)
        this.$message.error('获取解说员列表失败')
      } finally {
        this.loading = false
      }
    },
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getGuideList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        name: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getGuideList()
    },
    // 处理刷新
    handleRefresh() {
      this.getGuideList()
    },
    // 处理页码变化
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.getGuideList()
    },
    // 处理每页条数变化
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNum = 1
      this.getGuideList()
    },
    // 处理添加
    handleAdd() {
      this.dialogTitle = '添加解说员'
      this.editMode = false
      this.guideForm = {
        id: '',
        name: '',
        gender: 'MALE',
        // phone: '',
        language: '',
        introduction: '',
        status: 'AVAILABLE',
        photo: ''
      }
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑解说员'
      this.editMode = true
      this.guideForm = { ...row }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm(`确认删除解说员 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/guide/${row.id}`)
          if (res.code !== 200) {
            return this.$message.error(res.message || '删除解说员失败')
          }
          this.$message.success('删除解说员成功')
          this.getGuideList()
        } catch (error) {
          console.error('删除解说员失败', error)
          this.$message.error('删除解说员失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 处理图片点击事件
    handleImageClick() {
      this.$refs.fileInput.click()
    },
    // 处理文件选择变化
    handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return
      
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      
      // 将文件转换为base64
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.guideForm.photo = reader.result
        this.$message.success('图片上传成功')
      }
      reader.onerror = () => {
        this.$message.error('图片上传失败')
      }
      
      // 清空文件输入，以便于下次选择同一文件时也能触发change事件
      this.$refs.fileInput.value = ''
    },
    // 提交表单
    submitForm() {
      this.$refs.guideFormRef.validate(async valid => {
        if (!valid) return
        try {
          let res
          if (this.editMode) {
            // 编辑解说员
            res = await this.$http.put('/guide', this.guideForm)
          } else {
            // 添加解说员
            res = await this.$http.post('/guide', this.guideForm)
          }
          if (res.data.code !== 200) {
            return this.$message.error(res.data.message || '操作失败')
          }
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.getGuideList()
        } catch (error) {
          console.error('操作失败', error)
          this.$message.error('操作失败')
        }
      })
    }
  }
}
</script>

<style scoped>
.guide-manage-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}